#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <cstdio>
#include <vector>
#include "Pthread.hpp"

#define NUM 5
pthread_mutex_t pmt = PTHREAD_MUTEX_INITIALIZER;

int ticket = 10000;

void Buyticket(std::string name)
{
    while (true)
    {
        //加锁
        pthread_mutex_lock(&pmt);
        if (ticket > 0)
        {
            usleep(1000);
            printf("%s 正在抢票 ticket: %d\n", name.c_str(), ticket);
            ticket--;
            pthread_mutex_unlock(&pmt);
        }
        else
        {
            pthread_mutex_unlock(&pmt);
            break;
        }

        //抢票后续执行任务
        usleep(10000);
    }
}

int main()
{
    //单线程抢票
    // Thread<void, std::string> p1(Buyticket, GetPthreadName());
    // p1.Create();
    // p1.Jion();

    // //多线程抢票
    // Thread<void, std::string> p1(Buyticket, GetPthreadName());
    // Thread<void, std::string> p2(Buyticket, GetPthreadName());
    // Thread<void, std::string> p3(Buyticket, GetPthreadName());
    // Thread<void, std::string> p4(Buyticket, GetPthreadName());
    
    // p1.Create();
    // p2.Create();
    // p3.Create();
    // p4.Create();

    // p1.Jion();
    // p2.Jion();
    // p3.Jion();
    // p4.Jion();

    std::vector<Thread<void, std::string>> threads;
    for (int i = 0; i < NUM; i++)
    {
        threads.push_back(Thread<void, std::string>(Buyticket, GetPthreadName()));
    }

    for (auto& ts : threads)
    {
        ts.Create();
    }

    for (auto& ts : threads)
    {
        ts.Jion();
    }

    return 0;
}